﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using ShopOnline.Web;
using System.Windows.Data;
using System.ServiceModel.DomainServices.Client;

namespace ShopOnline.Views
{
    public partial class ViewOrders : Page
    {
        private DomainServiceShopOnline dsShopOnline;
        private PagedCollectionView orders;
        private const string FILTERED = "Orders filtered by status - \"";
        private const string FIND = "Order by id - ";

        public ViewOrders()
        {
            InitializeComponent();

            this.dsShopOnline = new DomainServiceShopOnline();
            this.dsShopOnline.PropertyChanged += dsShopOnline_PropertyChanged;
        }

        void dsShopOnline_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            this.busyIndicator.IsBusy = !this.busyIndicator.IsBusy;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.dsShopOnline.Load(this.dsShopOnline.GetOrdersQuery());
            this.dsShopOnline.Load(this.dsShopOnline.GetOrderStatusesQuery());
            this.orders = new PagedCollectionView(this.dsShopOnline.Orders);
            this.comboBoxStatuses.ItemsSource = this.dsShopOnline.OrderStatuses;
            this.comboBoxStatuses.SelectedValuePath = "OrderStatusID";
            this.comboBoxStatuses.DisplayMemberPath = "Status";
        }

        private void BindGridAndPager(PagedCollectionView collection, string searchMode)
        {
            if (collection.Count > 0)
            {
                ChangeVisibility(Visibility.Visible);
                this.textBlockResult.Text = searchMode;
                this.dataGridOrders.ItemsSource = collection;
                this.dataPagerOrders.Source = collection;
            }
            else
            {
                ChangeVisibility(Visibility.Collapsed);
                this.textBlockResult.Text = searchMode + " <no results>";
            }
        }

        private void ChangeVisibility(Visibility visibility)
        {
            this.dataGridOrders.Visibility = visibility;
            this.dataPagerOrders.Visibility = visibility;
        }

        private void buttonFilter_Click(object sender, RoutedEventArgs e)
        {
            var result = from order in this.dsShopOnline.Orders
                         where order.OrderStatusID == (int)comboBoxStatuses.SelectedValue
                         select order;
            this.orders = new PagedCollectionView(result);
            BindGridAndPager(this.orders, FILTERED +
                ((OrderStatuse)comboBoxStatuses.SelectedItem).Status + "\"");
            textBoxOrderID.Text = "";
            this.buttonFind.IsEnabled = false;
        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            Order currentOrder = (Order)dataGridOrders.SelectedItem;
            ChangeStatusChildWindow chageStatus = new ChangeStatusChildWindow(
                this.dsShopOnline, currentOrder);
            chageStatus.Show();
            chageStatus.Closed += chageStatus_Closed;
        }

        void chageStatus_Closed(object sender, EventArgs e)
        {
            ChangeStatusChildWindow changeStatus = (ChangeStatusChildWindow)sender;
            if (changeStatus.DialogResult == true)
            {
                this.dsShopOnline.SubmitChanges(OrderStatusChangedCallback, null);
                this.textBlockResult.Text = "";
                this.dataGridOrders.ItemsSource = null;
                this.dataPagerOrders.Source = null;
            }
            else
            {
                this.dsShopOnline.RejectChanges();                
            }
        }

        private void OrderStatusChangedCallback(SubmitOperation operation)
        {
            if (operation.HasError)
            {
                ErrorWindow errWindow = new ErrorWindow(operation.Error);
                errWindow.Show();
            }
            else
            {
                this.textBlockResult.Text = "Status changed";
            }
            this.busyIndicator.IsBusy = false;
        }

        private void buttonFind_Click(object sender, RoutedEventArgs e)
        {
            int orderId = 0;
            try
            {
                orderId = int.Parse(textBoxOrderID.Text);
                if (orderId > 0)
                {
                    var result = from order in this.dsShopOnline.Orders
                                 where order.OrderID == orderId
                                 select order;
                    this.orders = new PagedCollectionView(result);
                    BindGridAndPager(this.orders, FIND + orderId.ToString());
                    comboBoxStatuses.SelectedItem = null;                    
                }
                else
                {
                    this.textBoxOrderID.Text = string.Empty;
                    ChildWindow errorWin = new ErrorWindow("Order ID must be greather than 0!", "Incorrect order ID");
                    errorWin.Show();
                }
            }
            catch (Exception ex)
            {
                this.textBoxOrderID.Text = string.Empty;
                ChildWindow errorWin = new ErrorWindow(ex);
                errorWin.Show();
            }
        }

        private void textBoxOrderID_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (textBoxOrderID.Text.Trim() == string.Empty)
            {
                buttonFind.IsEnabled = false;
            }
            else
            {
                buttonFind.IsEnabled = true;
            }
        }
    }
}
